// 主应用程序模块
const App = {
  // 应用状态
  state: {
    filteredData: [],
    isLoading: false,
    currentDateRange: null,
    dataWorker: null,
    MAX_VISIBLE_POINTS: 2000
  },

  // 初始化应用
  init: function() {
    console.log('初始化智能房间占用预测系统...');
    
    // 添加样式
    this.addStyles();
    
    // 初始化Web Worker
    this.initWorker();
    
    // 预初始化所有图表
    this.preInitCharts();
    
    // 设置事件监听器
    this.setupEventListeners();
    
    // 设置导航
    this.setupNavigation();
    
    // 获取日期范围
    this.fetchDateRange();
    
    // 设置窗口调整大小事件
    this.setupResizeHandler();
    
    // 初始化预测页面
    this.initPredictionMain();
    
    console.log('应用初始化完成');
  },

  // 添加样式
  addStyles: function() {
    const style = document.createElement('style');
    style.textContent = `
      .tooltip-dot {
        display: inline-block;
        width: 10px;
        height: 10px;
        margin-right: 5px;
        border-radius: 50%;
      }
      
      .occupancy-data {
        font-weight: bold;
        margin-top: 5px;
      }
    `;
    document.head.appendChild(style);
  },

  // 初始化Web Worker
  initWorker: function() {
    if (!window.Worker) {
      console.warn('浏览器不支持Web Worker');
      return;
    }

    const workerCode = `
      self.addEventListener('message', function(e) {
        const { action, data, params } = e.data;
        
        if (action === 'downsample') {
          const result = downsampleData(data, params.maxPoints);
          self.postMessage({
            action: 'downsample_result',
            result: result
          });
        } else if (action === 'filter') {
          const result = filterByDate(data, params.startDate, params.endDate);
          self.postMessage({
            action: 'filter_result',
            result: result
          });
        } else if (action === 'prepare_chart_data') {
          const result = prepareChartData(data);
          self.postMessage({
            action: 'chart_data_ready',
            result: result
          });
        }
      });
      
      function downsampleData(data, maxPoints) {
        if (!data || data.length <= maxPoints) return data;
        const step = Math.ceil(data.length / maxPoints);
        const result = [];
        for (let i = 0; i < data.length; i += step) {
          result.push(data[i]);
        }
        return result;
      }
      
      function filterByDate(data, startDate, endDate) {
        if (!startDate || !endDate) return data;
        return data.filter(item => {
          const itemDate = item.StandardDate || item.Date;
          return itemDate >= startDate && itemDate <= endDate;
        });
      }
      
      function prepareChartData(data) {
        if (!data || data.length === 0) return {};
        
        const timeData = data.map(item => \`\${item.Date} \${item.Time}\`);
        
        const chartData = {
          timeData: timeData,
          tempData: {
            s1: data.map(item => item.S1_Temp),
            s2: data.map(item => item.S2_Temp),
            s3: data.map(item => item.S3_Temp),
            s4: data.map(item => item.S4_Temp)
          },
          lightData: {
            s1: data.map(item => item.S1_Light),
            s2: data.map(item => item.S2_Light),
            s3: data.map(item => item.S3_Light),
            s4: data.map(item => item.S4_Light)
          },
          soundData: {
            s1: data.map(item => item.S1_Sound),
            s2: data.map(item => item.S2_Sound),
            s3: data.map(item => item.S3_Sound),
            s4: data.map(item => item.S4_Sound)
          },
          otherData: {
            co2: data.map(item => item.S5_CO2),
            co2Slope: data.map(item => item.S5_CO2_Slope),
            pir1: data.map(item => item.S6_PIR),
            pir2: data.map(item => item.S7_PIR),
            occupancy: data.map(item => item.Room_Occupancy_Count)
          }
        };
        
        return chartData;
      }
    `;

    const blob = new Blob([workerCode], { type: 'application/javascript' });
    this.state.dataWorker = new Worker(URL.createObjectURL(blob));

    this.state.dataWorker.addEventListener('message', (e) => {
      const { action, result } = e.data;

      if (action === 'downsample_result') {
        this.state.filteredData = result;
        this.updateCharts();
      } else if (action === 'filter_result') {
        this.state.filteredData = result;
        this.state.dataWorker.postMessage({
          action: 'downsample',
          data: this.state.filteredData,
          params: { maxPoints: this.state.MAX_VISIBLE_POINTS }
        });
      } else if (action === 'chart_data_ready') {
        this.updateChartsWithProcessedData(result);
      }
    });
  },

  // 预初始化图表
  preInitCharts: function() {
    // 等待DOM加载完成
    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', () => {
        this.initAllCharts();
      });
    } else {
      this.initAllCharts();
    }
  },

  // 初始化所有图表
  initAllCharts: function() {
    // 初始化各个图表
    TemperatureChart.init('tempChart');
    LightChart.init('lightChart');
    SoundChart.init('soundChart');
    OtherSensorsChart.init('otherChart');
    
    // 连接图表实现联动
    ChartSync.connectCharts();
    
    console.log(`所有图表初始化完成，共 ${ChartSync.getChartCount()} 个图表`);
  },

  // 初始化预测主模块
  initPredictionMain: function() {
    const initAttempt = () => {
      if (window.PredictionMain && typeof window.PredictionMain.init === 'function') {
        console.log('[INFO] 初始化预测页面模块...');
        try {
          window.PredictionMain.init();
          console.log('[INFO] 预测页面模块初始化成功');
        } catch (error) {
          console.error('[ERROR] 预测页面模块初始化失败:', error);
        }
      } else {
        console.log('[INFO] 等待 PredictionMain 模块加载...');
        setTimeout(initAttempt, 100); // 100ms后重试
      }
    };
    
    initAttempt();
  },

  // 获取日期范围
  fetchDateRange: function() {
    fetch('/get_date_range')
      .then(response => response.json())
      .then(data => {
        this.state.currentDateRange = {
          start_date: data.min_date,
          end_date: data.max_date
        };
        this.setupDateInputs();
        this.loadData(); // 加载默认数据
      })
      .catch(error => {
        console.error('获取日期范围失败:', error);
        this.showError('获取日期范围失败');
      });
  },

  // 设置事件监听器
  setupEventListeners: function() {
    // 应用筛选按钮事件
    const applyFilterBtn = document.getElementById('apply-time-filter');
    if (applyFilterBtn) {
      applyFilterBtn.addEventListener('click', () => {
        this.applyTimeFilter();
      });
    }
    
    // 刷新数据按钮事件
    const refreshBtn = document.getElementById('refresh-data');
    if (refreshBtn) {
      refreshBtn.addEventListener('click', () => {
        this.loadData();
      });
    }
    
    console.log('事件监听器设置完成');
  },

  // 设置日期输入
  setupDateInputs: function() {
    const startDateInput = document.getElementById('startDate');
    const endDateInput = document.getElementById('endDate');
    
    if (this.state.currentDateRange && startDateInput && endDateInput) {
      startDateInput.value = this.state.currentDateRange.start_date;
      endDateInput.value = this.state.currentDateRange.end_date;
      startDateInput.min = this.state.currentDateRange.start_date;
      startDateInput.max = this.state.currentDateRange.end_date;
      endDateInput.min = this.state.currentDateRange.start_date;
      endDateInput.max = this.state.currentDateRange.end_date;
    }
  },

  // 加载数据
  loadData: function(startDate = null, endDate = null) {
    if (this.state.isLoading) return;
    
    this.state.isLoading = true;
    this.showSuccess('正在加载数据...');

    let url = '/get_data';
    const params = new URLSearchParams();
    
    if (startDate && endDate) {
      params.append('start_date', startDate);
      params.append('end_date', endDate);
      url += '?' + params.toString();
    }

    fetch(url)
      .then(response => {
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
      })
      .then(data => {
        if (data && data.length > 0) {
          console.log(`成功加载 ${data.length} 条数据`);
          
          // 使用Web Worker处理数据
          if (this.state.dataWorker) {
            this.state.dataWorker.postMessage({
              action: 'prepare_chart_data',
              data: data
            });
          } else {
            // 回退到主线程处理
            this.state.filteredData = data;
            this.updateCharts();
          }
          
          // 数据加载完成，不显示统计信息
        } else {
          this.showError('没有找到数据');
        }
      })
      .catch(error => {
        console.error('数据加载失败:', error);
        this.showError('数据加载失败: ' + error.message);
      })
      .finally(() => {
        this.state.isLoading = false;
      });
  },

  // 使用预处理数据更新图表
  updateChartsWithProcessedData: function(chartData) {
    if (!chartData.timeData || chartData.timeData.length === 0) {
      console.warn('没有可用的图表数据');
      return;
    }

    // 更新各个图表
    TemperatureChart.update(chartData.timeData, chartData.tempData);
    LightChart.update(chartData.timeData, chartData.lightData);
    SoundChart.update(chartData.timeData, chartData.soundData);
    OtherSensorsChart.update(chartData.timeData, chartData.otherData);
    
    console.log('所有图表更新完成');
  },

  // 更新图表（原有方法的简化版本）
  updateCharts: function() {
    if (!this.state.filteredData || this.state.filteredData.length === 0) {
      console.warn('没有可用数据');
      return;
    }

    const timeData = this.state.filteredData.map(item => `${item.Date} ${item.Time}`);
    
    const chartData = {
      timeData: timeData,
      tempData: {
        s1: this.state.filteredData.map(item => item.S1_Temp),
        s2: this.state.filteredData.map(item => item.S2_Temp),
        s3: this.state.filteredData.map(item => item.S3_Temp),
        s4: this.state.filteredData.map(item => item.S4_Temp)
      },
      lightData: {
        s1: this.state.filteredData.map(item => item.S1_Light),
        s2: this.state.filteredData.map(item => item.S2_Light),
        s3: this.state.filteredData.map(item => item.S3_Light),
        s4: this.state.filteredData.map(item => item.S4_Light)
      },
      soundData: {
        s1: this.state.filteredData.map(item => item.S1_Sound),
        s2: this.state.filteredData.map(item => item.S2_Sound),
        s3: this.state.filteredData.map(item => item.S3_Sound),
        s4: this.state.filteredData.map(item => item.S4_Sound)
      },
      otherData: {
        co2: this.state.filteredData.map(item => item.S5_CO2),
        co2Slope: this.state.filteredData.map(item => item.S5_CO2_Slope),
        pir1: this.state.filteredData.map(item => item.S6_PIR),
        pir2: this.state.filteredData.map(item => item.S7_PIR),
        occupancy: this.state.filteredData.map(item => item.Room_Occupancy_Count)
      }
    };

    this.updateChartsWithProcessedData(chartData);
  },

  // 应用时间过滤
  applyTimeFilter: function() {
    const startDate = document.getElementById('startDate').value;
    const endDate = document.getElementById('endDate').value;

    if (!startDate || !endDate) {
      this.showError('请选择开始和结束日期');
      return;
    }

    if (new Date(startDate) > new Date(endDate)) {
      this.showError('开始日期不能晚于结束日期');
      return;
    }

    this.loadData(startDate, endDate);
  },

  // 设置窗口调整大小处理
  setupResizeHandler: function() {
    const resizeObserver = new ResizeObserver(
      ChartUtils.throttle(() => {
        ChartSync.resizeAllCharts();
      }, 250)
    );

    // 观察图表容器
    const containers = ['tempChart', 'lightChart', 'soundChart', 'otherChart'];
    containers.forEach(id => {
      const container = document.getElementById(id);
      if (container) {
        resizeObserver.observe(container);
      }
    });
  },

  // 设置导航
  setupNavigation: function() {
    const navItems = document.querySelectorAll('.nav-item');
    const sections = document.querySelectorAll('.section');

    navItems.forEach((item, index) => {
      item.addEventListener('click', () => {
        // 移除所有活动类
        navItems.forEach(i => i.classList.remove('active'));
        sections.forEach(s => s.classList.remove('active'));

        // 添加活动类到当前项
        item.classList.add('active');
        sections[index].classList.add('active');

        // 根据不同页面执行相应操作
        if (index === 0) {
          // 数据可视化页面
          setTimeout(() => {
            // 确保图表容器可见后再调整尺寸
            this.ensureChartsContainerVisible();
            requestAnimationFrame(() => {
              ChartSync.resizeAllCharts();
            });
          }, 100);
        } else if (index === 1) {
          // 数据分析页面 - 暂无功能
          console.log('数据分析页面 - 功能开发中');
        } else if (index === 2) {
          // 占用预测页面
          setTimeout(() => {
            if (window.PredictionMain) {
              if (window.PredictionMain.isInitialized) {
                // 如果已经初始化，重新调整图表尺寸
                window.PredictionMain.resizeCharts();
                console.log('预测图表尺寸已调整');
              } else {
                // 首次初始化
                window.PredictionMain.init();
              }
            } else {
              console.error('[ERROR] PredictionMain 未加载');
            }
          }, 200);
        } else if (index === 3) {
          // 模型性能页面
          setTimeout(() => {
            if (window.ModelsPerformance) {
              if (window.ModelsPerformance.isInitialized) {
                // 如果已经初始化，重新调整图表尺寸
                window.ModelsPerformance.resizeCharts();
                console.log('模型性能图表尺寸已调整');
              } else {
                // 首次初始化
                window.ModelsPerformance.init();
              }
            } else {
              console.error('[ERROR] ModelsPerformance 未加载');
            }
          }, 200);
        }
      });
    });

    // 设置预测页面内部导航
    this.setupPredictionNavigation();
  },

  // 设置预测页面内部导航
  setupPredictionNavigation: function() {
    const predictionNavItems = document.querySelectorAll('.prediction-nav-item');
    const predictionTabContents = document.querySelectorAll('.prediction-tab-content');

    predictionNavItems.forEach((item) => {
      item.addEventListener('click', () => {
        const targetTab = item.getAttribute('data-tab');

        // 移除所有活动类
        predictionNavItems.forEach(i => i.classList.remove('active'));
        predictionTabContents.forEach(content => content.classList.remove('active'));

        // 添加活动类到当前项
        item.classList.add('active');
        
        // 显示对应的标签页内容
        const targetContent = document.querySelector(`[data-content="${targetTab}"]`);
        if (targetContent) {
          targetContent.classList.add('active');
        }

        // 根据不同标签页执行相应操作
        if (targetTab === 'occupancy') {
          // 占用预测标签页 - 重新调整图表大小
          setTimeout(() => {
            if (window.PredictionMain && window.PredictionMain.resizeCharts) {
              window.PredictionMain.resizeCharts();
            }
          }, 300);
        } else if (targetTab.startsWith('room')) {
          // Room数据标签页 - 可以在这里加载特定房间的数据
          console.log(`切换到 ${targetTab} 数据显示`);
          // TODO: 加载对应房间的数据
        }
      });
    });
  },

  // 显示错误信息
  showError: function(message) {
    console.error(message);
    
    // 显示错误消息到UI
    const errorDiv = document.getElementById('error-message');
    if (errorDiv) {
      errorDiv.textContent = message;
      errorDiv.style.display = 'block';
      
      // 3秒后自动隐藏
      setTimeout(() => {
        errorDiv.style.display = 'none';
      }, 3000);
    }
    
    // 隐藏加载提示
    const loadingDiv = document.getElementById('loading-message');
    if (loadingDiv) {
      loadingDiv.style.display = 'none';
    }
  },

  // 显示成功信息
  showSuccess: function(message) {
    console.log(message);
    
    // 隐藏错误消息
    const errorDiv = document.getElementById('error-message');
    if (errorDiv) {
      errorDiv.style.display = 'none';
    }
    
    // 隐藏加载提示，不显示成功消息
    const loadingDiv = document.getElementById('loading-message');
    if (loadingDiv) {
        loadingDiv.style.display = 'none';
    }
  },

  // 确保图表容器可见
  ensureChartsContainerVisible: function() {
    const chartIds = ['tempChart', 'lightChart', 'soundChart', 'otherChart'];
    
    chartIds.forEach(id => {
      const container = document.getElementById(id);
      if (container) {
        // 强制显示容器
        container.style.display = 'block';
        container.style.visibility = 'visible';
        
        // 检查容器尺寸
        const rect = container.getBoundingClientRect();
        if (rect.width === 0 || rect.height === 0) {
          // 强制设置最小尺寸
          container.style.minHeight = '300px';
          container.style.minWidth = '100%';
          // 强制重新计算布局
          container.offsetHeight;
        }
        
        console.log(`确保图表容器 ${id} 可见: ${container.offsetWidth}x${container.offsetHeight}`);
      }
    });
  },

  // 销毁应用
  destroy: function() {
    // 销毁所有图表
    TemperatureChart.dispose();
    LightChart.dispose();
    SoundChart.dispose();
    OtherSensorsChart.dispose();
    
    // 终止Web Worker
    if (this.state.dataWorker) {
      this.state.dataWorker.terminate();
      this.state.dataWorker = null;
    }
    
    console.log('应用已销毁');
  }
};

// 导出到全局
window.App = App;

// 页面加载完成后初始化应用
document.addEventListener('DOMContentLoaded', function() {
  App.init();
});

// 全局函数（保持向后兼容）
window.applyTimeFilter = function() {
  App.applyTimeFilter();
}; 